package cn.com.api.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.api.entity.ApiNews;
import cn.com.api.entity.ApiT_products;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiType;
import cn.com.api.mapper.ApiCarMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiGoodsMapper;
import cn.com.api.mapper.ApiNewsMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiTypeMapper;
import cn.com.api.service.ApiCommonService;
import cn.com.api.service.ApiShopsService;
import cn.com.api.service.ApiTypeService;
import cn.com.api.service.CheckService;
import cn.com.api.service.SystemService;
import cn.com.response.ApiResponsePage;
import cn.com.response.ApiResultPage;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_API + "type/")
public class ApiTypeController {

	@Autowired
	private ApiTypeService apitypeService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private ApiNewsMapper apiNewsMapper;

	@Autowired
	private ApiTypeMapper apiTypeMapper;
	@Autowired
	private ApiTmemberMapper apiTMemberMapper;
	@Autowired
	private ApiCarMapper apiCarMapper;
	@Autowired
	private ApiGoodsMapper apiGoodsMapper;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiCommonService apiCommonService;
	@Autowired
	private CheckService checkService;
	@Autowired
	private ApiShopsService apiShopsService;

	private static Logger logger = Logger.getLogger(ApiTypeController.class);

	// 查询二级分类
	@RequestMapping("/gettwoType")
	public void gettwoType(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		String cid = request.getParameter("c_id");
		Integer c_id = Integer.parseInt(cid);
		List<ApiType> list = apitypeService.gettwoType(c_id);
		PrintWriter out = response.getWriter();
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put("list", list);
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	// 查询是三级分类
	@RequestMapping("/getthreeType")
	public void getthreeType(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		String cid = request.getParameter("c_id");
		Integer c_id = Integer.parseInt(cid);
		List<ApiType> list = apitypeService.getthreeType(c_id);
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put("list", list);
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	@RequestMapping("/getGoodsType")
	public void getGoodsType(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		PrintWriter out = response.getWriter();
		String cBelong = request.getParameter("c_Belong");
		System.out.println(cBelong);
		List<Map<String, Object>> list = apitypeService.getGoodsType(cBelong);
		/* 手动添加非一级分类 但需要在品类页面左侧显示的 */
		// Map<String, Object> shengXian = new HashMap<String, Object>();
		// shengXian = apitypeService.searShengXian();
		// list.add(shengXian);
		//
		out.print(JsonUtil.object2json(list));
		out.close();

	}

	/**
	 * --@ResponseBody Object APP首页加载
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getIndex")
	public void getIndex(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ApiResponsePage apiResponse = new ApiResponsePage();
		ApiResultPage result = new ApiResultPage();
		// 验证标志位
		boolean bChk = true;
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> l = new HashMap<String, Object>();
		try {

			// 查询数据库
			if (bChk) {

				/* 12个按钮需要图片,对应的字段有图片字段,在数据库中存入图片的名称,手机端有对应的图片名称一一对应即可 */
				// l.put("menutype", StartOnLoadService.oneList);
				// 重新查询获取12个按钮的方法
				List<ApiType> list = apitypeService.getTypesByCBelong(0);
				l.put("menutype", list);
				/* 根据业务查询对应的表,得到数据将值保存到map中 */
				map.put("datas", l);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作成功");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex);
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE,
					Utils.getMessage(request, "API_ERROR_UNKNOW", null));
		}
		result.setResponse(apiResponse);
		systemService.logApiPage(request, result);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();

	}

	/**
	 * 12个按钮跳转到子页面--5种不同的显示方式
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "goTypeDetails")
	public void goTypeDetails(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String cCode = request.getParameter("cCode");
			String city_id = request.getParameter("city_id");
			String pageCount = request.getParameter("pageCount");
			Map<String, String> params = new HashMap<String, String>();
			params.put("cCode", cCode);
			params.put("city_id", city_id);
			params.put("pageCount", pageCount);

			if (checkService.checkParams(params, map)) {
				apitypeService.searchTypeGoods(map, params);
			}

		} catch (Exception e) {
			logger.info(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		map.put("key", 1);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 测试
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "test")
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<ApiNews> adsList = apiNewsMapper.selectApiNews();
		List<ApiType> types = apiTypeMapper.getTypesByCBelong(0);
		ApiTmember member = apiTMemberMapper.findMemberByCuserid("18621566012");
		// ApiTmemberPage memberPage2 =
		// apiTMemberMapper.saveApiTmemberTest(memberPage);
		List<Integer> cIds = new ArrayList<Integer>();
		cIds.add(55);
		cIds.add(56);
		cIds.add(61);
		cIds.add(62);
		/** 定时任务测试 */
		// apiCommonService.autoAllocateTask();
		// apiCommonService.cancelOverTimeOrders();
		// apiCommonService.allocateOrderTask("X20160116104137693");
		// apiCommonService.allocateOrderTaskManually("", "18621560001");

		// 配送端消息推送测试
		// apiCommonService.remindSenderNewTask("18621566012",
		// "H186215660122015123010013901047");

		// List<CarOrderPage> carList = apiCarMapper.searchCarGoodsByCids(cIds);
		// map.put("data1", adsList);
		// map.put("data2", types);
		// map.put("data4", member);
		// map.put("carList", carList);
		// map.put("data5", memberPage2);

		// List<ApiDingDan> dingDanList =
		// apiDingDanMapper.searchNewOrdersNotPay();

		// 分页技术
		// PageInfo page = new PageInfo();
		// page.setShowCount(10);// 每页显示的记录数
		// page.setCurrentPage(1);
		// List<ApiType> typeList = apitypeService.getApiTypeListPage(page);
		// map.put("typeList", dingDanList);
		// map.put("typeList-size", typeList.size());
		// map.put("typeList-sumpage", page.getTotalPage());

		// 测试库存问题
		// int flag =
		// apiT_productsMapper.reduceProductByProductId((long)100000290, 1);
		// map.put("flag", flag);
		String[] ordersId = "HNLY20160310060920389,HNLY20160311060359123"
				.split(",");
		List<ApiT_products> list = apiT_productsMapper
				.findProductNotEnoughByOrdersId(ordersId);
		System.out.println("list:" + list);
		map.put("list", list);

		response.setCharacterEncoding("GBK");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * insert
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "insertType")
	public void insertType(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String c_name = request.getParameter("c_name");
		String c_des = request.getParameter("c_des");
		String c_sid = request.getParameter("c_sid");

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("c_name", c_name);
		params.put("c_sid", c_sid);
		try {
			if (checkService.checkParams(params, map)) {
				ApiType type = new ApiType();
				Integer shop_id = Integer.valueOf(c_sid);
				type.setcSid(shop_id);
				type.setcName(c_name);
				type.setcDes(c_des);
				type.setcEnable(1);
				type.setcSort(0);
				type.setcIsziying(0);
				type.setcAdmin("");
				type.setcAlias("");
				type.setcMod("品类");
				type.setcKeyword(c_name);
				type.setcStatus(1);
				type.setSources("app");
				apitypeService.insertType(type);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "添加成功！");
			}
		} catch (Exception e) {
			logger.info(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 根据id查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/findTypeById")
	public void findTypeById(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String c_code = request.getParameter("c_code");
		ApiType type = apitypeService.findTypeById(Integer.valueOf(c_code));

		// response
		response.setCharacterEncoding("UTF-8");
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "查询成功！");
		map.put("datas", type);
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 根据id查询 该接口用户端和商家端都用 商家端type=1
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getTypesByShopId")
	public void getTypesByShopId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			String c_sid = request.getParameter("c_sid");
			String type = request.getParameter("type");//
			Integer shop_id = Integer.valueOf(c_sid);
			List<ApiType> typeList = new ArrayList<ApiType>();
			List<ApiType> types = apitypeService.getTypesByShopId(Integer
					.valueOf(c_sid));
			ApiType tt = null;
			// 美食外卖需要添加热销榜分类---先判断是否是美食外卖的店铺
			if (Util.isNull(type) || !"1".equals(type)) {// 用户端
				tt = apitypeService.getMeiShiTypeByShopId(c_sid);
				if (tt != null) {
					typeList.add(tt);
				}
			}
			if (types != null && types.size() > 0) {
				for (ApiType t : types) {
					Integer c_code = t.getcCode();
					Integer type_count = apiGoodsMapper
							.getGoodsCountByTypeIdAndShopId(c_code, shop_id);
					t.setGoods_count(type_count);
				}
				typeList.addAll(types);
			}

			map.put("datas", typeList);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功！");
		} catch (Exception e) {
			logger.error(e);
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		// response
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 修改
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "updateT_type")
	public void updateT_type(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String id = request.getParameter("id");
		String c_name = request.getParameter("c_name");
		String c_des = request.getParameter("c_des");

		Map<String, Object> map = new HashMap<String, Object>();

		try {
			if (id != null && !"".equals(id.trim())) {
				ApiType t_type = new ApiType();
				// 获取原数据
				t_type = apitypeService.findTypeById(Integer.valueOf(id));
				// 修改
				t_type.setcName(c_name);
				t_type.setcDes(c_des);
				//
				apitypeService.updateType(t_type);

				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "编辑成功！");
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "检查失败！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "deleteT_type")
	public void deleteT_type(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			if (id != null && !"".equals(id.trim())) {

				Integer ret_I = apitypeService.deleteType(Integer.parseInt(id));
				if (ret_I > 0) {
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "删除成功！");
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "检查失败！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 软删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "disableT_type")
	public void disableT_type(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String id_list = request.getParameter("id_list");
		String enable = request.getParameter("enable"); // enable:0

		Map<String, Object> map = new HashMap<String, Object>();

		try {
			String[] ids = id_list.split(",");
			for (String id : ids) {
				if (id != null && !"".equals(id.trim())) {
					ApiType t_type = new ApiType();
					// 获取原数据
					t_type = apitypeService.findTypeById(Integer.valueOf(id));
					// 修改
					t_type.setcEnable(Integer.valueOf(enable));
					//
					apitypeService.updateType(t_type);
				}
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "软删除成功！");
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 软删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "getTypesByParent")
	public void getTypesByParent(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String parentid = request.getParameter("parentid");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<ApiType> list = apitypeService.getTypesByParent(Integer
					.valueOf(parentid));
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功");
			map.put(Utils.DATAS, list);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

}
